process.env.NTBA_FIX_319 = 1;
const TelegramBot = require('node-telegram-bot-api');
const Agent = require('socks5-https-client/lib/Agent');

const logger = require('./src/logger');
const upload = require('./src/upload');
const Sticker = require('./src/sticker');
const protobuf = require('./src/protobuf');
const Config = require('./config/server.json');

async function main() {
    // 创建机器人
    let options = {
        polling: {
            params: {
                timeout: 5000
            },
            autoStart: true
        }
    };
    if (Config.bot_agent) {
        options.request = {
            timeout: 5000,
            agentClass: Agent,
            agentOptions: {
                socksHost: Config.bot_agent.host,
                socksPort: Config.bot_agent.port,
            }
        }; 
    }
    const bot = new TelegramBot(Config.bot_token, options);

    // 监听export命令
    bot.onText(/\/export/, async (msg, _) => {
        // 检查消息合法性
        const chatId = msg.chat.id;
        if (!msg.reply_to_message || !msg.reply_to_message.sticker) {
            bot.sendMessage(chatId, '请 **Reply** 一条 Sticker 消息。', {
                parse_mode: 'Markdown',
                reply_to_message_id: msg.message_id,
            });
            return;
        }

        if (msg.reply_to_message.sticker.is_animated) {
            bot.sendMessage(chatId, '暂不支持动态 Sticker 拷贝。', {
                reply_to_message_id: msg.message_id,
            });
            return;
        }

        // 下载Sticker包
        let stickerSet = null;
        try {
            stickerSet = await Sticker.downloadStickerSet(bot, chatId, msg.message_id, msg.reply_to_message.sticker.set_name);
        } catch (error) {
            await bot.sendMessage(chatId, '下载 Sticker 包失败，请稍后再试', {
                reply_to_message_id: msg.message_id,
            });
            return;
        }

        // 生成Manifest文件
        let stickers = [];
        for (let idx = 0; idx < stickerSet.stickers.length; idx++) {
            const sticker = stickerSet.stickers[idx];
            stickers.push(protobuf.Sticker(idx, sticker.emoji));
        }
        const manifest = protobuf.EncodeStickerPack(stickerSet.title, 'Official', stickers);

        // 加密Sticker包文件
        let result = null;
        try {
            result = await Sticker.encryptStickerSet(bot, chatId, msg.message_id, manifest, stickerSet);
        } catch (error) {
            await bot.sendMessage(chatId, '加密 Sticker 包失败，请稍后再试', {
                reply_to_message_id: msg.message_id,
            });
            return;
        }

        // 上传Sticker包文件
        let packId = null;
        try {
            packId = await upload.uploadStickerSet(bot, chatId, msg.message_id, result.encryptedManifest, result.stickerSet);
        } catch (error) {
            await bot.sendMessage(chatId, '上传 Sticker 包失败，请稍后再试', {
                reply_to_message_id: msg.message_id,
            });
            return;
        }

        const count = stickers.length;
        const text = `拷贝 Sticker 包成功！\n\n**Title**: \`${stickerSet.title}\`\n**Count**: \`${count}\`\n**PackId**: \`${packId}\`\n**Key**: \`${result.base64Key}\``
        await bot.sendMessage(chatId, text, { parse_mode: 'Markdown', reply_to_message_id: msg.message_id });
    });

    logger.info('signal sticker bot started');
}

main();
